package com.mingyizhudao.app.utils;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import com.dixiang.framework.utils.SharedPreferenceUtils;
import com.dixiang.framework.utils.Utils;
import com.mingyizhudao.app.view.WebViewActivity;
import com.mingyizhudao.app.view.login.LoginActivity;
import com.mingyizhudao.app.view.login.LoginActivity2;
import com.mingyizhudao.app.view.recommend.CreateOrderActivity;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.graphics.Rect;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.widget.Toast;

public class CommonUtils {
	/**
	 * 获取包名
	 * 
	 * @author kong
	 * @createDate 2014-4-21
	 * @param
	 * @return
	 */
	public static String getPackageName(Context c) {
		String str = "";
		PackageManager manager = c.getPackageManager();
		try {
			PackageInfo info = manager.getPackageInfo(c.getPackageName(), 0);
			str = info.packageName; // 包名
		} catch (NameNotFoundException e) {
			e.printStackTrace();
		}
		return str;
	}

	/**
	 * 获得APP的版本名称
	 * 
	 * @param c
	 *            上下文
	 * @return 返回版本名称(例如: 3.2.1)
	 */
	public static String getAppVersionName(Context c) {
		try {
			PackageManager manager = c.getPackageManager();
			PackageInfo info = manager.getPackageInfo(c.getPackageName(), 0);
			return info.versionName;
		} catch (NameNotFoundException e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 获得APP的版本编号
	 * 
	 * @param c
	 *            上下文
	 * @return 返回版本名称(例如: 3.2.1)
	 */
	public static int getAppVersionCode(Context c) {
		try {
			PackageManager manager = c.getPackageManager();
			PackageInfo info = manager.getPackageInfo(c.getPackageName(), 0);
			return info.versionCode;
		} catch (NameNotFoundException e) {
			e.printStackTrace();
		}
		return 0;
	}

	public static String post(String actionUrl, Map<String, String> params,
			Map<String, File> files) throws IOException {

		String BOUNDARY = java.util.UUID.randomUUID().toString();
		String PREFIX = "--", LINEND = "\r\n";
		String MULTIPART_FROM_DATA = "multipart/form-data";
		String CHARSET = "UTF-8";
		URL uri = new URL(actionUrl);
		HttpURLConnection conn = (HttpURLConnection) uri.openConnection();
		conn.setReadTimeout(10 * 1000);
		conn.setDoInput(true);// 允许输入
		conn.setDoOutput(true);// 允许输出
		conn.setUseCaches(false);
		conn.setRequestMethod("POST"); // Post方式
		conn.setRequestProperty("connection", "keep-alive");
		conn.setRequestProperty("Charsert", "UTF-8");
		conn.setRequestProperty("Content-Type", MULTIPART_FROM_DATA
				+ ";boundary=" + BOUNDARY);

		// 首先组拼文本类型的参数
		StringBuilder sb = new StringBuilder();
		for (Map.Entry<String, String> entry : params.entrySet()) {
			sb.append(PREFIX);
			sb.append(BOUNDARY);
			sb.append(LINEND);
			sb.append("Content-Disposition: form-data; name=\""
					+ entry.getKey() + "\"" + LINEND);
			sb.append("Content-Type: text/plain; charset=" + CHARSET + LINEND);
			sb.append("Content-Transfer-Encoding: 8bit" + LINEND);
			sb.append(LINEND);
			sb.append(entry.getValue());
			sb.append(LINEND);
		}

		DataOutputStream outStream = new DataOutputStream(
				conn.getOutputStream());
		outStream.write(sb.toString().getBytes());

		// 发送文件数据
		if (files != null)
			for (Map.Entry<String, File> file : files.entrySet()) {
				StringBuilder sb1 = new StringBuilder();
				sb1.append(PREFIX);
				sb1.append(BOUNDARY);
				sb1.append(LINEND);
				sb1.append("Content-Disposition: form-data; name=\""
						+ file.getKey() + "\"; filename=\""
						+ file.getValue().getPath() + "\"" + LINEND);
				sb1.append("Content-Type: image/jpeg"
					+ LINEND);
				
//				sb1.append("Content-Type: application/octet-stream; charset="
//								+ CHARSET + LINEND);
				sb1.append(LINEND);
				outStream.write(sb1.toString().getBytes());
				InputStream is = new FileInputStream(file.getValue());
				byte[] buffer = new byte[1024];
				int len = 0;
				while ((len = is.read(buffer)) != -1) {
					outStream.write(buffer, 0, len);
				}

				is.close();
				outStream.write(LINEND.getBytes());
			}

		// 请求结束标志
		byte[] end_data = (PREFIX + BOUNDARY + PREFIX + LINEND).getBytes();
		outStream.write(end_data);
		outStream.flush();

		// 得到响应码
		int res = conn.getResponseCode();
		InputStream in = conn.getInputStream();
		InputStreamReader isReader = new InputStreamReader(in);
		BufferedReader bufReader = new BufferedReader(isReader);
		String line = null;
		String data = "OK";
		String upRes = null;
		while ((line = bufReader.readLine()) == null)
			data += line;
		
		if (res == 200) {
			int ch;
			StringBuilder sb2 = new StringBuilder();
			while ((ch = in.read()) != -1) {
				sb2.append((char) ch);
			}
			
			upRes = sb2.toString();
		}
		outStream.close();
		conn.disconnect();
		
		return upRes;
	}

	@SuppressLint("SimpleDateFormat")
	public static String transformDte(String type, String dateString,
			String toType) {
		SimpleDateFormat sdf = new SimpleDateFormat(type);
		SimpleDateFormat sdf2 = new SimpleDateFormat(toType);
		String toDateString = null;
		try {
			if (dateString != null) {
				Date date = sdf.parse(dateString);
				toDateString = sdf2.format(date);
			} else {
				return null;
			}
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return toDateString;
	}

	// 获取状态栏高度
	public static int getStatusHeight(Activity activity) {
		int statusHeight = 0;
		Rect localRect = new Rect();
		activity.getWindow().getDecorView()
				.getWindowVisibleDisplayFrame(localRect);
		statusHeight = localRect.top;
		if (0 == statusHeight) {
			Class<?> localClass;
			try {
				localClass = Class.forName("com.android.internal.R$dimen");
				Object localObject = localClass.newInstance();
				int i5 = Integer.parseInt(localClass
						.getField("status_bar_height").get(localObject)
						.toString());
				statusHeight = activity.getResources()
						.getDimensionPixelSize(i5);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return statusHeight;
	}

	public static void goToWebView(Context mContext, String title,
			String actionUrl) {
		Bundle bundle = new Bundle();
		bundle.putString(Constants.PARM_PAGE_TITLE, title);
		bundle.putString(Constants.PARM_ACTION_URL, actionUrl);
		IntentHelper.getInstance(mContext).gotoActivity(WebViewActivity.class,
				bundle);
	}
	public static void goToCreateOrder(Context context, String id,
			String doctorName, String hpDept, String hpName, String actionUrl,
			boolean isDept) {
		goToCreateOrder(context, id, doctorName, hpDept, hpName, actionUrl, isDept, false);
	}
	
	public static void goToCreateOrder(Context context, String id,
			String doctorName, String hpDept, String hpName, String actionUrl,
			boolean isDept , boolean is_commonweal) {
		String token = getToken(context);
		if (token == null || token.length() == 0 || token.equals("null")) {
			IntentHelper.getInstance(context).gotoActivity(LoginActivity2.class);
			return;
		}
		Bundle bundle = new Bundle();
		bundle.putString(Constants.ORDER.PARM_ORDER_DOCTOR_ID, id);
		bundle.putString(Constants.ORDER.PARM_ORDER_DOCTOR_NAME, doctorName);
		bundle.putString(Constants.ORDER.PARM_ORDER_DOCTOR_DEPT, hpDept);
		bundle.putString(Constants.ORDER.PARM_ORDER_DOCTOR_HP, hpName);
		bundle.putString(Constants.PARM_ACTION_URL, actionUrl);
		bundle.putBoolean(Constants.PARM_ORDER_TYPE, isDept);
		bundle.putBoolean(Constants.PARM_ORDER_COMMONWEAL, is_commonweal);
		IntentHelper.getInstance(context).gotoActivity(
				CreateOrderActivity.class, bundle);
	}
	

	public static String getMobile(Context context) {
		return (String) SharedPreferenceUtils.getInstance(context,
				Constants.APPINFO).get(Constants.MOBILE);
	}

	public static String getToken(Context context) {
		return (String) SharedPreferenceUtils.getInstance(context,
				Constants.APPINFO).get(Constants.USERTOKEN);
	}

	public static void setMobile(Context context, String mobile) {
		SharedPreferenceUtils.getInstance(context, Constants.APPINFO).save(
				Constants.MOBILE, mobile);
	}

	public static void setToken(Context context, String token) {
		SharedPreferenceUtils.getInstance(context, Constants.APPINFO).save(
				Constants.USERTOKEN, token);
	}
	
	/**
	 * 获取本地数据
	 * @param context
	 * @return
	 */
	public static String getLocaldataFromNetUrl(Context context) {
		String localdataUrl = (String) SharedPreferenceUtils.getInstance(context,Constants.APPINFO).get("localdataUrl");
		if(!( localdataUrl!=null&&localdataUrl.length()>0)){
			localdataUrl = Constants.baseURL + "localdata";
		}
		return localdataUrl;
	}
	
	public static void setLocaldataFromNetUrl(Context context, String localdataUrl) {
		SharedPreferenceUtils.getInstance(context, Constants.APPINFO).save("localdataUrl", localdataUrl);
	}
	
	/**
	 * 获取验证码
	 * @param context
	 * @return
	 */
	public static String getSendCodeUrl(Context context) {
		String sendCodeUrl = (String) SharedPreferenceUtils.getInstance(context,Constants.APPINFO).get("sendCodeUrl");
		if(!( sendCodeUrl!=null&&sendCodeUrl.length()>0)){
			sendCodeUrl = Constants.baseURL + "smsverifycode";
		}
		return sendCodeUrl;
	}
	
	public static void setSendCodeUrl(Context context, String sendCodeUrl) {
		SharedPreferenceUtils.getInstance(context, Constants.APPINFO).save("sendCodeUrl", sendCodeUrl);
	}
	
	/**
	 * 用户登录地址
	 * @param context
	 * @return
	 */
	public static String getLoginUrl(Context context) {
		String loginUrl = (String) SharedPreferenceUtils.getInstance(context,Constants.APPINFO).get("loginUrl");
		if( !( loginUrl!=null&&loginUrl.length()>0) ){
			loginUrl = Constants.baseURL + "usermobilelogin";
		}
		return loginUrl;
	}
	
	
	public static void setLoginUrl(Context context, String loginUrl) {
		SharedPreferenceUtils.getInstance(context, Constants.APPINFO).save("loginUrl", loginUrl);
	}
	
	
	/**
	 * 用户登录地址
	 * @param context
	 * @return
	 */
	public static String getLoginByPwdUrl(Context context) {
		String loginUrl = (String) SharedPreferenceUtils.getInstance(context,Constants.APPINFO).get("userlogin");
		if( !( loginUrl!=null&&loginUrl.length()>0) ){
			loginUrl = Constants.baseURL + "userlogin";
		}
		return loginUrl;
	}
	
	
	public static void setLoginByPwdUrl(Context context, String loginUrl) {
		SharedPreferenceUtils.getInstance(context, Constants.APPINFO).save("userlogin", loginUrl);
	}
	
	
	
	public static String getRegisterUrl(Context context){
		String registerUrl = (String) SharedPreferenceUtils.getInstance(context,Constants.APPINFO).get("registerUrl");
		if( !( registerUrl!=null&&registerUrl.length()>0) ){
			registerUrl = Constants.baseURL + "userregister";
		}
		return registerUrl;
	}
	
	public static void setRegisterUrl(Context context, String registerUrl) {
		SharedPreferenceUtils.getInstance(context, Constants.APPINFO).save("registerUrl", registerUrl);
	}
	
	
	public static String getResetPswUrl(Context context){
		String resetUrl = (String) SharedPreferenceUtils.getInstance(context,Constants.APPINFO).get("resetUrl");
		if( !( resetUrl!=null&&resetUrl.length()>0) ){
			resetUrl = Constants.baseURL + "userresetpassword";
		}
		return resetUrl;
	}
	
	public static void setResetUrl(Context context, String resetUrl) {
		SharedPreferenceUtils.getInstance(context, Constants.APPINFO).save("resetUrl", resetUrl);
	}
	
	
	public static void setPaymentUrl(Context context ,String paymentUrl){
		SharedPreferenceUtils.getInstance(context, Constants.APPINFO).save("paymentUrl", paymentUrl);
	}
	
	/**
	 * 订单支付地址
	 * @param context
	 * @return
	 */
	public static String getPaymentUrl(Context context){
		String paymentUrl = (String) SharedPreferenceUtils.getInstance(context,Constants.APPINFO).get("paymentUrl");
		if( !( paymentUrl!=null&&paymentUrl.length()>0) ){
			paymentUrl = "http://md.mingyizhudao.com/mobiledoctor/order/view?refNo=#&os=#&header=0&footer=0&addBackBtn=0&app=0";
		}
		return paymentUrl;
	}
	
	/**
	 * 预约列表地址
	 * @param context
	 * @return
	 */
	public static String getBookingListUrl(Context context) {
		String bookingListUrl = (String) SharedPreferenceUtils.getInstance(context,Constants.APPINFO).get("bookingListUrl");
		if( !( bookingListUrl!=null&&bookingListUrl.length()>0) ){
			bookingListUrl = Constants.baseURL + "userbooking";
		}
		return bookingListUrl;
	}
	
	public static void setBookingListUrl(Context context, String bookingListUrl) {
		SharedPreferenceUtils.getInstance(context, Constants.APPINFO).save("bookingListUrl", bookingListUrl);
	}
	
	public static void setBookingUrl(Context context, String bookingUrl){
		SharedPreferenceUtils.getInstance(context, Constants.APPINFO).save("bookingUrl", bookingUrl);
	}
	
	/**
	 * 预约地址
	 * @param context
	 * @return
	 */
	public static String getBookingUrl(Context context){
		String bookingUrl = (String) SharedPreferenceUtils.getInstance(context,Constants.APPINFO).get("bookingUrl");
		if( !( bookingUrl!=null&&bookingUrl.length()>0) ){
			bookingUrl = Constants.baseURL + "booking";
		}
		return bookingUrl;
	}
	
	/**
	 * 获取医生详情
	 * @param context
	 * @return
	 */
	public static String getDoctorUrl(Context context){
		String doctorUrl = (String) SharedPreferenceUtils.getInstance(context,Constants.APPINFO).get("doctorUrl");
		if( !( doctorUrl!=null&&doctorUrl.length()>0) ){
			doctorUrl = Constants.baseURL + "doctor/";
		}
		return doctorUrl;
	}
	
	public static void setDoctoUrl(Context context ,String doctorUrl){
		SharedPreferenceUtils.getInstance(context, Constants.APPINFO).save("doctorUrl", doctorUrl);
	}
	
	
	/**
	 * 获取医院科室详情
	 * @param context
	 * @return
	 */
	public static String getHospitalUrl(Context context){
		String hospitalUrl = (String) SharedPreferenceUtils.getInstance(context,Constants.APPINFO).get("hospitalUrl");
		if( !( hospitalUrl!=null&&hospitalUrl.length()>0) ){
			hospitalUrl = Constants.baseURL + "hospital/";
		}
		return hospitalUrl;
	}
	
	public static void setHospitalUrl(Context context ,String hospitalUrl){
		SharedPreferenceUtils.getInstance(context, Constants.APPINFO).save("hospitalUrl", hospitalUrl);
	}
	
	/**
	 * 获取预约资料
	 * @param context
	 * @return
	 */
	public static String getBookingfileUrl(Context context){
		String bookingfileUrl = (String) SharedPreferenceUtils.getInstance(context,Constants.APPINFO).get("bookingfileUrl");
		if( !( bookingfileUrl!=null&&bookingfileUrl.length()>0) ){
			bookingfileUrl = Constants.baseURL + "bookingfile";
		}
		return bookingfileUrl;
	} 
	
	
	public static void setBookingfileUrl(Context context ,String bookingfileUrl){
		SharedPreferenceUtils.getInstance(context, Constants.APPINFO).save("bookingfileUrl", bookingfileUrl);
	}
	
	
	public static String getDataVersion(Context context) {
		String dataVersion = (String) SharedPreferenceUtils.getInstance(context,Constants.APPINFO).get("dataVersion");
		if( !( dataVersion!=null&&dataVersion.length()>0) ){
			dataVersion = "0";
		}
		return dataVersion;
	}
	
	public static void setDataVersion(Context context, String dataVersion) {
		SharedPreferenceUtils.getInstance(context, Constants.APPINFO).save("dataVersion", dataVersion);
	}
	
	public static void initRefreshState(){
		Constants.IS_TEAM_NEAD_REFRESH = true;
		Constants.IS_SCALPEL_NEAD_REFRESH = true;
		Constants.IS__HOSPITAL_NEAD_REFRESH = true;
	}

	
	public static String getTokenParam(Activity activity){
		return "?username="+CommonUtils.getMobile( activity )+"&token="+CommonUtils.getToken( activity );
	}

	public static String getPayUrl(Context activity,String refno){
		String url = getPaymentUrl(activity);
		if(Utils.isStringEmpty(url)){
			return "";
		}
		url = url.replaceFirst("#", refno);
		url = url.replaceFirst("#", "android");
		return url;
	}
	
	
	
	/**
	 * 获取是否要显示引导页         1代表展示过了
	 * @param context
	 * @return
	 */
	public static String getIsShowedGuide(Context context) {
		String isShowGuide = (String) SharedPreferenceUtils.getInstance(context,Constants.APPINFO).get(""+getAppVersionCode(context));
		if(!( isShowGuide!=null&&isShowGuide.length()>0)){
			isShowGuide = "0";
		}
		return isShowGuide;
	}
	
	public static void setIsShowedGuide(Context context, String isShowGuide) {
		SharedPreferenceUtils.getInstance(context, Constants.APPINFO).save(""+getAppVersionCode(context), isShowGuide);
	}
	
	
	
	public static void doPut(final String url, final String json,final Handler handler){

		
		new Thread(new Runnable() {
			@Override
			public void run() {
				try{	
					//创建一个http客户端  
					HttpClient client=new DefaultHttpClient();  
					//创建一个PUT请求  
					HttpPut httpPut=new HttpPut(url);  
					//组装数据放到HttpEntity中发送到服务器  
					final List dataList = new ArrayList();  
					StringEntity entity = new StringEntity(json.toString(),"utf-8");
					httpPut.setEntity(entity);  
					//向服务器发送PUT请求并获取服务器返回的结果，可能是修改成功，或者失败等信息  
					HttpResponse response=client.execute(httpPut);  
					Message msg = new Message();
					if (response != null) {
						StatusLine statusLine = response.getStatusLine();
						int statusCode = statusLine.getStatusCode();
						if(statusCode == 200 || statusCode == 403 ){
							InputStream inputStream = response.getEntity().getContent();
							if(inputStream != null){
								String result = getResult(inputStream);

								msg.what = Constants.Result_Status.RESULT_SCCESS;
								msg.obj = result;
								handler.sendMessage(msg);
							}
						}
					}else {
						msg.what = Constants.Result_Status.RESULT_FAILURE;
						handler.sendMessage(msg);
					}
				}catch(Exception ex){
					ex.printStackTrace();
				}
			}
		}).start();

	}
	
	private static String getResult(InputStream inputStream){
		try{
			byte[] buffer = new byte[2048];
			int readBytes = 0;
			StringBuilder stringBuilder = new StringBuilder();
			while((readBytes = inputStream.read(buffer)) > 0){
				stringBuilder.append(new String(buffer, 0, readBytes));
			}
			return stringBuilder.toString();
		}catch(Exception ex){
			ex.printStackTrace();
		}
		return null;
	}
	
	/**
	 * 获取医生详情
	 * @param context
	 * @return
	 */
	public static String getBenefitUrl(Context context){
		String doctorUrl = (String) SharedPreferenceUtils.getInstance(context,Constants.APPINFO).get("benefitUrl");
		if( !( doctorUrl!=null&&doctorUrl.length()>0) ){
			doctorUrl = "http://m.mingyizhudao.com/mobile/home/page/view/myzy/agent/app/addBackBtn/0/header/0/footer/0/app/0";
		}
		return doctorUrl;
	}
	
	public static void setBenefitUrl(Context context ,String doctorUrl){
		SharedPreferenceUtils.getInstance(context, Constants.APPINFO).save("benefitUrl", doctorUrl);
	}
	
	
	public static void showErrorAtBottom(final Context context,Handler handler, final String msg){
		handler.post(new Runnable() {
			@Override
			public void run() {
					Toast.makeText(context, msg, Toast.LENGTH_LONG).show();	
			}
		});
	}
	
	public static void showHttpError(final Context context,Handler handler, final int msg){
		handler.post(new Runnable() {
			@Override
			public void run() {
					Toast.makeText(context, "网络访问错误："+msg, Toast.LENGTH_LONG).show();	
			}
		});
	}
}
